package com.borqsprocessmanager.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ComposePathEffect;
import android.graphics.CornerPathEffect;
import android.graphics.DiscretePathEffect;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.graphics.Typeface;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.ArcShape;
import android.graphics.drawable.shapes.OvalShape;
import android.graphics.drawable.shapes.RectShape;
import android.graphics.drawable.shapes.RoundRectShape;
import android.graphics.drawable.shapes.Shape;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.borqsprocessmanager.App;
import com.borqsprocessmanager.BatteryManager;
import com.borqsprocessmanager.Constant;
import com.borqsprocessmanager.IService;
import com.borqsprocessmanager.MainActivity;
import com.borqsprocessmanager.ProcessSettingManager;
import com.borqsprocessmanager.R;
import com.borqsprocessmanager.adapter.SampleAdapter;
import com.borqsprocessmanager.adapter.SampleAdapter.OnItemButtonClickListener;
import com.borqsprocessmanager.db.DBProvider.SamplesTable;
import com.borqsprocessmanager.db.DBProvider.WhiteListTable;
import com.borqsprocessmanager.info.ProcessStatsInfo;
import com.borqsprocessmanager.info.ReceiverProcessInfo;
import com.borqsprocessmanager.util.DBAsyncWorker;
import com.borqsprocessmanager.util.IShowSampleRes;
import com.borqsprocessmanager.util.Log;
import com.borqsprocessmanager.util.PreferencesUtil;
import com.borqsprocessmanager.view.ActionPopWindow;
import com.borqsprocessmanager.view.progressbar.MyProgressBar;

public class ResultFragment extends BaseFragment implements IShowSampleRes,
        OnItemButtonClickListener, OnClickListener, OnItemClickListener {
    private final String TAG = "ResultFragment";

    // private BatteryManagerService mService;
    private BatteryManager mBatteryManager;

    public View layout;
    private ViewGroup mLevelItemLayout, mTimeItemLayout;
    private View mHeader;
    private TextView mTimeTextData;
    private ListView mResListView;
    private ImageView mWhiteButton;
    private MyProgressBar mPowerPorgressBar;

    private Typeface mFace;

    private ActionPopWindow mActionPopWindow;
    private SampleAdapter mItemAdapter;
    private ReceiverProcessInfo disableInfo;
    private HashMap<String, ReceiverProcessInfo> mAutoStartMap;
    private ArrayList<ProcessStatsInfo> mProcessList;

    private String mPackageName;

    private boolean isWhiteList = false;
    private boolean isAutoStart = false;
    private int mItemPosation;
    private int mPowerLevel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.v(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        initData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        layout = inflater.inflate(R.layout.result_fragment, null);

        findView(layout);
        return layout;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        addHeader(mResListView);
    }

    private void initData() {
        mFace = Typeface.createFromAsset(App.mContext.getAssets(),
                "fonts/Roboto-Thin.ttf");
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.v(TAG, "onStart");
        showResUI();
        getWhiteMap();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void findView(View layout) {
        mResListView = (ListView) layout.findViewById(R.id.main_list);
        // mLevelItemLayout = (ViewGroup) layout
        // .findViewById(R.id.res_fragment_level);
        mTimeItemLayout = (ViewGroup) layout
                .findViewById(R.id.res_fragment_time);
        // setListLayoutAnimation(mLevelItemLayout);
        // setListLayoutAnimation(mTimeItemLayout);
        mTimeTextData = (TextView) mTimeItemLayout
                .findViewById(R.id.time_hour_text_data);
        mActionPopWindow = new ActionPopWindow(mActivity, this);

        mPowerPorgressBar = (MyProgressBar) layout
                .findViewById(R.id.time_progressbar);
    }

    /**
     * 获得最新的siampleId,根据id从Db中查找数据，放入List中显示。是异步通过Async获得数据的。
     */
    private void showResUI() {
        Log.v(TAG, "showResUI");
        boolean isNewData = mActivity.isNewData();
        MainActivity.simpleId = getSiampleId();
        if (isNewData) {
            // 提醒进入第一次
            PreferencesUtil.getInstance(App.mContext).putBoolean(
                    Constant.KEY_IS_NEWDATA, false);
            mTimeItemLayout.setVisibility(View.GONE);
            new DBAsyncWorker(this).execute(MainActivity.simpleId - 1);
            // new DBAsyncWorker(this).execute(5);
        } else if (mProcessList != null && mProcessList.size() > 0) {
            // 在提醒后，没有退出Activity之前，不重查数据库，使用上次数据
            showSampleRes(mProcessList);
        } else {
            showBatteryInfo();
        }
    }

    private void addHeader(ListView list) {
        LayoutInflater inflater = LayoutInflater.from(App.mContext);
        mHeader = inflater.inflate(R.layout.result_list_head, null);
        if (!mActivity.isNewData()) {
            mHeader.findViewById(R.id.res_list_head_line).setVisibility(
                    View.INVISIBLE);
        } else {
            mHeader.findViewById(R.id.res_list_head_shadowline).setVisibility(
                    View.INVISIBLE);
        }
        mWhiteButton = (ImageView) mHeader
                .findViewById(R.id.res_list_head_white);
        mWhiteButton.setOnClickListener(this);
        mResListView.addHeaderView(mHeader, null, false);
    }

    private void showWhiteButton() {
        if (isWhiteList) {
            mWhiteButton.setVisibility(View.VISIBLE);
        } else {
            mWhiteButton.setVisibility(View.INVISIBLE);
        }
    }

    private void getWhiteMap() {
        final Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (mWhiteMap != null) {
                    HashMap<String, ProcessStatsInfo> whiteMap = mWhiteMap;
                    if (whiteMap != null && whiteMap.size() > 0) {
                        isWhiteList = true;
                    } else {
                        isWhiteList = false;
                    }
                }
                showWhiteButton();
                return true;
            }
        });
        handler.sendEmptyMessageDelayed(0, 100);
    }

    private void showBatteryInfo() {
        final Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                Log.v(TAG, "noWarring");
                // 没有提醒，给出“正常”item
                // showSampleRes(new ArrayList<ProcessStatsInfo>());
                if (mPersonService != null) {
                    try {
                        Log.v(TAG, "mPersonService");
                        mPowerLevel = mPersonService.getCurBatteryLevel();
                        float argTime = mPersonService.getArgTimeM();
                        Log.v(TAG, "argTime==" + argTime);
                        mPowerPorgressBar.setmProgessEnd(mPowerLevel);
                        mPowerPorgressBar.startAnimaction();
                        if (mPowerLevel != 0) {
                            setBatteryLevelItem(mPowerLevel);
                            // if (argTime != 0) {
                            // setbatteryTimeItem(38, 1f);
                            setbatteryTimeItem(mPowerLevel, argTime);
                            // }
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                return true;
            }
        });
        handler.sendEmptyMessage(0);
    }

    @Override
    public void showSampleRes(ArrayList<ProcessStatsInfo> list) {
        mProcessList = list;
        Log.v(TAG, "showSampleRes");
        if (mProcessList != null && mProcessList.size() > 0) {
            if (mActivity.isRoot) {
                try {
                    mAutoStartMap = ProcessSettingManager
                            .getCompoentProcessMap("android.net.conn.CONNECTIVITY_CHANGE");
                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        setAdapter(mResListView, mProcessList);
    }

    private void setAdapter(ListView listView, ArrayList<ProcessStatsInfo> list) {
        Log.v(TAG, "setAdapter");
        mItemAdapter = new SampleAdapter(mActivity, list);
        listView.setAdapter(mItemAdapter);
        listView.setOnItemClickListener(this);
        mItemAdapter.setOnItemClickListener(this);
        setListViewListener(mResListView, mItemAdapter);
        if (mActivity.isNewData()) {
            setListLayoutAnimation(listView);
        } else {
            listView.clearAnimation();
        }
    }

    private void setListLayoutAnimation(ViewGroup viewGroup) {
        Log.v(TAG, "setListLayoutAnimation");
        AnimationSet set = new AnimationSet(true);

        Animation animation = new AlphaAnimation(0.0f, 1.0f);
        animation.setDuration(600);
        set.addAnimation(animation);
        animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, -1.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                -0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        animation.setDuration(500);
        set.addAnimation(animation);
        LayoutAnimationController controller = new LayoutAnimationController(
                set, 0.2f);
        viewGroup.setLayoutAnimation(controller);
    }

    @Override
    public void onItemButtonClick(View v, int posation) {
        mItemPosation = posation;
        isAutoStart = false;
        ProcessStatsInfo info = mProcessList.get(mItemPosation);
        disableInfo = new ReceiverProcessInfo();
        disableInfo.setAppName(info.appName);
        disableInfo.setPackageName(info.packageName);
        disableInfo.setProcessName(info.processName);
        disableInfo.setIsClose(ReceiverProcessInfo.CLOSE);
        // disableInfo = mProcessList.get(mItemPosation);
        // ArrayList<ReceiverProcessInfo> enableInfo = mActivity.mService
        // .getReceiverInfo();

        // for (ReceiverProcessInfo activityInfo : enableInfo) {
        // if (activityInfo.packageName.equals(mPackageName)) {
        // isAutoStart = true;
        // disableInfo = activityInfo;
        // break;
        // }
        // }
        // if (isAutoStart) {
        boolean isAutoProcess = mBatteryManager.isAutoStartProcess(
                mAutoStartMap, disableInfo.packageName);
        if (isAutoProcess && !mActivity.isRoot) {
            mActionPopWindow.showPop(ActionPopWindow.TYPE_NOROOT_AUTOPROCESS);
        } else if (isAutoProcess) {
            mActionPopWindow
                    .showPop(ActionPopWindow.TYPE_UNINSTILL_AND_KILLPROCESS);
        } else {
            mActionPopWindow.showPop(ActionPopWindow.TYPE_ONLY_UNINSTILL);
        }
    }

    // } else {
    // ActionDialog.showDialog(mActivity, this,
    // ActionDialog.TYPE_ONLY_UNINSTILL);
    // }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
        case R.id.dialog_left_layout:
            ProcessSettingManager.uninstillApp(mActivity,
                    disableInfo.packageName);
            mActionPopWindow.dissmisDialog();
            // mItemAdapter.remove(mItemPosation);
            // mItemAdapter.notifyDataSetChanged();
            break;
        case R.id.dialog_right_layout:
            HashMap<String, ReceiverProcessInfo> mDisableMap = new HashMap<String, ReceiverProcessInfo>();
            mDisableMap.put(disableInfo.packageName, disableInfo);
            mBatteryManager.saveDisableMapForDB(mActivity.isRoot,
                    mAutoStartMap, mDisableMap);
            mActionPopWindow.dissmisDialog();
            mItemAdapter.remove(mItemPosation);
            mItemAdapter.notifyDataSetChanged();
            break;
        case R.id.res_list_head_white:
            String[] tag = App.mContext.getResources().getStringArray(
                    R.array.action_list_fragment);
            mActivity.addFragment(tag[3], MainActivity.TYPE_SLIDE_LEFT, true);
            break;
        default:

            break;
        }
    }

    @Override
    protected void dismisListViewItem(int position) {
        Animation shake = AnimationUtils.loadAnimation(App.mContext,
                R.anim.scale);
        mWhiteButton.startAnimation(shake);
        ProcessStatsInfo info = mProcessList.get(position);
        saveWhiteList(info);
        addWhiteFromMap(info);
        if (!isWhiteList) {
            isWhiteList = true;
            showWhiteButton();
        }
    }

    private void addWhiteFromMap(ProcessStatsInfo info) {
        if (info != null) {
            mWhiteMap.put(info.packageName, info);
        }
    }

    private boolean getWhiteList() {
        return isAutoStart;
    }

    @Override
    public void setArguments(Bundle args) {
        // TODO Auto-generated method stub
        super.setArguments(args);
    }

    @Override
    public void onBindServiced(IService personService,
            HashMap<String, ReceiverProcessInfo> actionMap,
            HashMap<String, ProcessStatsInfo> whiteMap) {
        super.onBindServiced(personService, actionMap, whiteMap);
        mBatteryManager = new BatteryManager(actionMap);
        if (whiteMap != null && whiteMap.size() > 0) {
            isWhiteList = true;
        }
    }

    private void saveWhiteList(ProcessStatsInfo info) {
        ContentValues value = new ContentValues();
        // value.put(ProcessTable.PID, info.pid);
        value.put(WhiteListTable.UID, info.uid);
        value.put(WhiteListTable.APP_NAME, info.appName);
        value.put(WhiteListTable.PKG_NAME, info.packageName);
        value.put(WhiteListTable.PROCESS_NAME, info.processName);
        value.put(WhiteListTable.IS_SYSTEM, info.isSystem);
        value.put(WhiteListTable.RATIO, info.ratio);
        value.put(WhiteListTable.TX_BYTES, info.tx);
        value.put(WhiteListTable.RX_BYTES, info.rx);
        value.put(WhiteListTable.TOTAL_BYTES, info.total);
        value.put(WhiteListTable.SAMPLE_ID, info.sampleId);
        value.put(WhiteListTable.TYPE, info.type);

        App.mContext.getContentResolver().insert(WhiteListTable.CONTENT_URI,
                value);
    }

    private int getSiampleId() {
        int id = 1;
        Cursor cursor = mActivity.getContentResolver().query(
                SamplesTable.CONTENT_URI,
                new String[] { SamplesTable._ID + "" }, null, null, null);
        if (null != cursor && cursor.getCount() > 0) {
            cursor.moveToFirst();
            id = (cursor.getInt(cursor.getColumnIndex(SamplesTable._ID))) + 1;
            cursor.close();
            Log.v(TAG, "simpleId===" + id);
        }
        PreferencesUtil.getInstance(App.mContext)
                .putInt(Constant.SAMPLE_ID, id);

        Intent intent = new Intent(Constant.ACTION_SAMPLE_ID);
        intent.putExtra(Constant.SAMPLE_ID, id);
        // mActivity.sendBroadcast(intent);
        return id;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        if (position > 0) {
            Log.v(TAG, "onItemClick");
            onItemButtonClick(view, position - 1);
            View moreView = view.findViewById(R.id.res_more_layout);
            initMoreTextData(moreView, position - 1);
            int visibility = moreView.getVisibility();
            if (visibility == View.GONE) {
                moreView.setVisibility(View.VISIBLE);
                Log.v(TAG, "onItemClick_VISIBLE");
            } else {
                moreView.setVisibility(View.GONE);
                Log.v(TAG, "onItemClick_GONE");
            }
        }
    }

    /**
     * @param moreView
     * @param position
     */
    private void initMoreTextData(View moreView, int position) {
        ProcessStatsInfo info = mProcessList.get(position);
        long networkData = info.total;
        double ratio = info.ratio;
        Log.v(TAG, "info.name===" + info.appName + "");
        Log.v(TAG, "info.ratio===" + ratio + "");
        Log.v(TAG, "info.type===" + info.type + "");
        TextView net = (TextView) moreView.findViewById(R.id.res_more_text_net);
        TextView netData = (TextView) moreView
                .findViewById(R.id.res_more_text_net_data);
        TextView cpu = (TextView) moreView.findViewById(R.id.res_more_text_cpu);
        TextView cpuData = (TextView) moreView
                .findViewById(R.id.res_more_text_cpu_data);

        if (networkData != 0) {
            Log.v(TAG, "info.total===" + networkData + "");
            cpu.setVisibility(View.GONE);
            cpuData.setVisibility(View.GONE);
            netData.setText(networkData / 1024 + "kb");
        }
        if (ratio != 0) {
            net.setVisibility(View.GONE);
            netData.setVisibility(View.GONE);
            cpuData.setText(ratio + "%");
        }
    }

    private void setBatteryLevelItem(int level) {
        // mLevelItemLayout.setVisibility(View.VISIBLE);
        TextView batteryLevel = (TextView) layout
                .findViewById(R.id.time_level_text);
        // TextView batterylevelTitle = (TextView) mLevelItemLayout
        // .findViewById(R.id.prompt_level_title);
        // batteryLevel.setTypeface(mFace);

        Log.v(TAG, "level==" + level);
        batteryLevel.setText(level + "%");
        // if (level == 100) {
        // batterylevelTitle.setText(getResources().getString(
        // R.string.battery_full));
        // }
    }

    private void setbatteryTimeItem(int level, Float argTime) {
        // mTimeItemLayout.setVisibility(View.VISIBLE);
        TextView batteryTime = (TextView) mTimeItemLayout
                .findViewById(R.id.time_hour_text);
        batteryTime.setTypeface(mFace);
        if (level != 0 && argTime != 0) {
            batteryTime.setText((int) (level * (argTime)) + "");
        } else {
            batteryTime.setText("");
            mTimeTextData.setVisibility(View.INVISIBLE);
        }
    }
}
